package com.pactera.chat.websocket;


import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

import javax.websocket.CloseReason;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpoint;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pactera.chat.bean.ChatMsg;
import com.pactera.chat.bean.ChatUser;
import com.pactera.chat.bean.WebSocketMsg;
import com.pactera.chat.mapper.util.CustomConfigurator;


/**
 * @author s-team_zhang
 * @version 1.0 
 */
@ServerEndpoint(value = "/chat",configurator = CustomConfigurator.class)
public class ChatOnline{
	private static Map<String,ChatUser> userMap = new ConcurrentHashMap<>();
	private static Map<String,Session> sessionMap = new ConcurrentHashMap<>();
	private static Map<String,String> sessionHostMap = new ConcurrentHashMap<>();
	private static List<ChatUser> chatUsers = new CopyOnWriteArrayList<>();
	@OnMessage
	public void onMessage(Session session, String msg){
		WebSocketMsg webSocketMsg = JSON.parseObject(msg, WebSocketMsg.class);
		if("online".equals(webSocketMsg.getMsgType())){
			ChatUser usr = JSONObject.parseObject(webSocketMsg.getMsg().toString(), ChatUser.class);
			ChatUser usr1 = JSONObject.parseObject(webSocketMsg.getMsg().toString(), ChatUser.class);
			String host = usr.getHost();
			if(!chatUsers.contains(usr1)){
				chatUsers.add(usr1);
			}
			usr.setSession(session);
			if(!userMap.containsKey(host)){
				userMap.put(host, usr);
			}
			
			if(!sessionMap.containsKey(session)){
				sessionMap.put(session.getId(), session);
			}
			
			if(!sessionHostMap.containsKey(session)){
				sessionHostMap.put(session.getId(), host);
			}
			
			for (Entry<String, ChatUser> entry : userMap.entrySet()) {
				try {
					if(entry.getValue().getSession().isOpen()){
						String jsonString = JSON.toJSONString(chatUsers);
						System.out.println(jsonString);
						entry.getValue().getSession().getBasicRemote().sendText(jsonString);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
//			ChatMsg chatMsg = new ChatMsg();
			return ;
		}
		
 		if("chatSingle".equals(webSocketMsg.getMsgType())){
			ChatMsg chatMsg = JSONObject.parseObject(webSocketMsg.getMsg().toString(), ChatMsg.class);;
			for (Entry<String, ChatUser> entry : userMap.entrySet()) {
				if(sessionHostMap.containsKey(session.getId())){
					String host = sessionHostMap.get(session.getId());
					
					if(userMap.containsKey(host)){
						ChatUser chatUser = userMap.get(host);
						if(StringUtils.isNotBlank(chatUser.getAlias())){
							chatMsg.setFromUsr(chatUser.getAlias());
						}
					}
				}
				
				try {
					entry.getValue().getSession().getBasicRemote().sendText(JSON.toJSONString(chatMsg));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return ;
		}
		
		if("chatGroup".equals(webSocketMsg.getMsgType())){
			
			return ;
		}
		
		
	}
	
	@OnOpen
	public void onOpen(final Session session, EndpointConfig config){
		HandshakeRequest req = (HandshakeRequest) config.getUserProperties().get("handshakereq");
		Map<String,List<String>> headers = req.getHeaders();
		
	}
	
	@OnClose
	public void onClose(final Session session,CloseReason reason){
		String id = session.getId();
		String host  = sessionHostMap.get(id);
		userMap.remove(host);
		sessionHostMap.remove(id);
		sessionMap.remove(id);
		for (ChatUser chatUser : chatUsers) {
			if(host.equals(chatUser.getHost())){
				chatUsers.remove(chatUser);
			}
		}
	}
	
	@OnError
	public void onError(Session session, Throwable t){
		t.printStackTrace();
	}
}
